<template>
  <div class="channelEdit">
    <!-- 我的频道 -->
    <van-cell class="myChannels" :border="false">
      <div slot="title">我的频道</div>
      <van-button
        type="danger"
        plain
        size="mini"
        round
        class="editBtn"
        @click="isEdit = !isEdit"
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <!-- 宫格:我的频道 -->
    <van-grid :border="false" gutter="10px" class="my_grid">
      <van-grid-item
        :text="item.name"
        v-for="(item, index) in myChannels"
        :key="item.id"
        :class="index === active ? 'active' : ''"
        :icon="index === 0 ? '' : isEdit ? 'clear' : ''"
        @click="checkOrEdit(item, index)"
      />
    </van-grid>
    <!-- 频道推荐 -->
    <van-cell :border="false" class="proChannels">
      <div slot="title">频道推荐</div>
    </van-cell>
    <!-- 宫格:频道推荐 -->
    <van-grid :border="false" gutter="10px" class="pro_grid">
      <van-grid-item
        icon="plus"
        :text="item.name"
        v-for="item in proChannels"
        :key="item.id"
        @click="addChannel(item)"
      />
    </van-grid>
  </div>
</template>

<script>
// 获取用户频道列表
// import { getUserChannels } from '@/api/user'
// 获取全部用户频道列表
import {
  getAllChannels,
  addUserChannel,
  deleteUserChannel
} from '@/api/channel'
// 导入vuex 容器
import { mapState } from 'vuex'
// 导入存储方法
import { setItem } from '@/utils/storage'

export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      // myChannels: [],
      allChannels: [],
      isEdit: false // 判断是否是编辑状态
    }
  },
  async created() {
    // 直接组件传值即可
    // try {
    //   const res = await getUserChannels()
    //   const { channels } = res.data.data
    //   this.myChannels = channels
    // } catch (error) {
    //   this.$toast.fail('用户频道查询失败')
    // }

    try {
      const res = await getAllChannels()
      //   console.log(res)
      const { channels } = res.data.data
      //   console.log(channels.length)
      this.allChannels = channels
    } catch (error) {
      this.$toast.fail('全部频道查询失败')
    }
  },
  mounted() {},
  activited() {},
  update() {},
  beforeRouteUpdate() {},
  methods: {
    // 将推荐频道添加到我的频道
    async addChannel(channel) {
      this.myChannels.push(channel)

      // 添加频道持久化 判断userToken 是否有效
      if (this.userToken) {
        // 登录状态下,保存到服务端
        try {
          const params = { id: channel.id, seq: this.myChannels.length }
          await addUserChannel(params)
        } catch (error) {
          this.$toast.fail('保存失败!')
        }
      } else {
        // 非登录状态下 保存到本地
        setItem('MYCHANNELS', this.myChannels)
      }
    },

    // 判断是否是编辑状态,我的频道体现不同的功能
    checkOrEdit(item, index) {
      // 编辑状态,点击删除
      if (this.isEdit) {
        // const i = this.myChannels.findIndex(t => t.id === item.id)
        if (index !== 0) {
          // 也可以定义一个数组来控制固定的频道,更灵活
          this.myChannels.splice(index, 1)
          if (index < this.active) {
            this.$emit('changeActive')
          }

          // 实现数据持久化
          this.deleteUserChannel(item.id)
        }
      } else {
        // 非编辑状态下,点击切换频道
        // 子组件向父组件传值:激活索引,关闭弹出层
        this.$emit('changeChannel', index)
      }
    },

    // 持久化删除用户指定频道
    async deleteUserChannel(id) {
      if (this.userToken) {
        // 登录状态
        try {
          await deleteUserChannel(id)
        } catch (error) {
          this.$toast.fail('保存失败!')
        }
      } else {
        // 未登录状态下
        setItem('MYCHANNELS', this.myChannels)
      }
    }
  },
  filter: {},
  computed: {
    ...mapState(['userToken']),
    // 全部频道减去已选频道
    proChannels() {
      //   const channelsArr = JSON.parse(JSON.stringify(this.allChannels))
      //   this.myChannels.forEach(item1 => {
      //     const i = channelsArr.findIndex(item2 => {
      //       return item1.id === item2.id
      //     })
      //     channelsArr.splice(i, 1)
      //   })
      //   return channelsArr
      return this.allChannels.filter(item1 => {
        return !this.myChannels.find(item2 => {
          return item2.id === item1.id
        })
      })
    }
  },
  watch: {}
}
</script>

<style lang="less" scoped>
.channelEdit {
  padding-top: 28px;
}
.myChannels {
  margin-top: 48px;
  font-size: 32px;
  color: #333333;
}
.proChannels {
  margin-top: 48px;
  font-size: 32px;
  color: #333333;
}
.editBtn {
  width: 108px;
  height: 48px;
  color: #f86363;
}
/deep/ .active {
  .van-grid-item__text {
    color: rgb(247, 10, 50) !important;
  }
}
</style>
